/*
 * Copyright 2019 <徐志涛>
 * 2024.12.25
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package org.qengine.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.qengine.entity.PaperRulesEntity;
import org.qengine.service.PaperRulesService;
import org.qengine.service.PapersService;
import org.qengine.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.qengine.vo.PaperRulesVo;
import org.qengine.entity.QuestionEntity;

import java.util.List;
import java.util.Random;

@Slf4j
@RestController
@RequestMapping("/paperRules")
public class PaperRulesController {


    @Autowired
    private PaperRulesService paperRulesService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private PapersService papersService;
    //规则的精确查询与模糊查询
    @GetMapping("/FindRule")
    public ResponseEntity<?> getPaperRules(@RequestBody PaperRulesVo paperRulesVo, @RequestParam(defaultValue = "1") int current,
                                           @RequestParam(defaultValue = "10") int size) {
        try {
            log.info("FindRequest received for ruleId: {}, courseId: {}, knowledgeSelId: {}, problemSelType: {}, dSelLevel: {}", paperRulesVo.getRuleId(), paperRulesVo.getCourseId(), paperRulesVo.getKnowledgeSelId(), paperRulesVo.getProblemSelType(), paperRulesVo.getDSelLevel());
            if (paperRulesVo.getRuleId() != null) {
                PaperRulesEntity result = paperRulesService.getPaperRules(paperRulesVo.getRuleId());
                log.info("precise FindResponse returned: {}", result);
                return ResponseEntity.ok(result);
            } else {
                IPage<PaperRulesEntity> results = paperRulesService.findPaperRulesByConditions(
                        paperRulesVo.getCourseId(),
                        paperRulesVo.getKnowledgeSelId(),
                        paperRulesVo.getProblemSelType(),
                        paperRulesVo.getDSelLevel(),
                        current,
                        size
                );
                if (results.getRecords().isEmpty()) {
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No matching rules found");
                }
                log.info("FindResponse returned: {}", results);
                return ResponseEntity.ok(results);
            }
        } catch (Exception e) {
            log.error("Error occurred while fetching paper rules: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error fetching paper rules");
        }
    }


    @GetMapping("/SaveRules")
    public String savePaperRules(@RequestBody PaperRulesVo paperRulesVo) {
        try {
            log.info("SaveRequest received for ruleId: {}, courseId: {}, knowledgeSelId: {}, problemSelType: {}, dSelLevel: {}", paperRulesVo.getRuleId(), paperRulesVo.getCourseId(), paperRulesVo.getKnowledgeSelId(), paperRulesVo.getProblemSelType(), paperRulesVo.getDSelLevel());
            String result1 = paperRulesService.savePaperRules(paperRulesVo);
            log.info("SaveResponse returned: {}", result1);
            return result1;
        } catch (Exception e) {
            log.error("Error occurred while saving paper rules: {}", e.getMessage());
            return "Error saving new paper rules";
        }
    }


    @GetMapping("/DeleteRules")
    public String DeleteRules(@RequestParam Long ruleId) {
        try {
            paperRulesService.getPaperRules(ruleId);


            log.info("DeleteRequest received for ruleId: {}", ruleId);
            String result1 = paperRulesService.delPaperRules(paperRulesService.getPaperRules(ruleId));
            log.info("DeleteResponse returned: {}", result1);
            return result1;
        } catch (Exception e) {
            log.error("Error occurred while deleting paper rules: {}", e.getMessage());
            return "Error deleting new paper rules";
        }
    }

    //分页查询全部规则，可输入参数为当前页数和总页数
    @GetMapping("/AllPaperRules")
    public IPage<PaperRulesEntity> getPaperRules(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        return paperRulesService.getPaperRulesPage(current, size);
    }

    //根据选择的rule生成试卷
    @GetMapping("/GeneratePaper")
    public ResponseEntity<?> GeneratePaper(@RequestParam Long ruleId) {
        try {
            log.info("GeneratePaperRequest received for ruleId: {}", ruleId);
            List<QuestionEntity> result1 = paperRulesService.GeneratePaper(ruleId);
            log.info("GeneratePaperResponse returned: {}", result1);
            papersService.savePapers(result1, ruleId,"Test");
            return ResponseEntity.ok(result1);

        } catch (Exception e) {
            log.error("Error occurred while generating paper: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating paper");
        }
    }

    @GetMapping("/Practice")
    public ResponseEntity<?> GeneratePracticeByCourseId(@RequestParam Long courseId) {
        PaperRulesEntity randomRule = null;
        List<QuestionEntity> result1 = null;
        try {
            log.info("GeneratePracticeByCourseIdRequest received for courseId: {}", courseId);
            IPage<PaperRulesEntity> pageResult = paperRulesService.findPaperRulesByConditions(courseId, null, null, null, 1, 10);
            List<PaperRulesEntity> rulesList = pageResult.getRecords();
            if (!rulesList.isEmpty()) {
                Random random = new Random();
                int randomIndex = random.nextInt(rulesList.size()); // 根据列表大小生成随机索引
                randomRule = rulesList.get(randomIndex); // 根据随机索引获取规则

                log.info("随机选取的规则: {}", randomRule);
            } else {
                log.warn("没有可用的规则");
            }
            try {
                if (randomRule == null) {
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No matching rules found");
                } else {
                    result1 = paperRulesService.GeneratePaper(randomRule.getRuleId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("GeneratePracticeByCourseIdResponse returned: {}", result1);
            papersService.savePapers(result1, randomRule.getRuleId(),"PracticeByCourse");
            return ResponseEntity.ok(result1);
        } catch (Exception e) {
            log.error("Error occurred while generating practice paper: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating practice paper");
        }

    }
//根据选择的rule生成训练题
    @GetMapping("/Training")
    public ResponseEntity<?> GenerateTrainingByMistakes(@RequestParam Long userId, @RequestParam Long ruleId) {
        PaperRulesEntity randomRule = null;
        List<QuestionEntity> result1 = null;
        try {
            log.info("GenerateTrainingByMistakesRequest received for ruleId: {}", ruleId);
            try {
                result1 = paperRulesService.GeneratePaper(ruleId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("GenerateTrainingByCourseIdResponse returned: {}", result1);
            papersService.savePapers(result1, ruleId,"Training");
            return ResponseEntity.ok(result1);
        } catch (Exception e) {
            log.error("Error occurred while generating Training paper: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating Training paper");
        }

    }
//错题库的记录
    @GetMapping("/Marking")
    public String GenerateMarkingByMistakes(@RequestParam String list, @RequestParam Long paperId) {
        return questionService.testMarks(list, paperId);
    }
    @GetMapping("/wrong")
    public List<QuestionEntity> getWrongQuestions() {
        return paperRulesService.getWrongQuestions();
    }
}


